package juc;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo3 {
    public static void main(String[] args) {
        //多个线程操作统一资源Car
        Car2 car = new Car2();

        //1的司机开这辆车
        new Thread(()->{
            for(int i = 0; i < 20 ; i++){
                car.driverThisBus(1);
            }
        },"A").start();

        //2的司机开这辆车
        new Thread(()->{
            for(int i = 0; i < 20 ; i++){
                car.driverThisBus(2);
            }
        },"B").start();

        //3的司机开这辆车
        new Thread(()->{
            for(int i = 0; i < 20 ; i++){
                car.driverThisBus(3);
            }
        },"C").start();

    }
}

class Car2{
    private String carCode = "闽D66666";

    private int id = 0;

    //该变量为了查看锁的影响
    private int time = 0;

    Lock lock = new ReentrantLock();

    public synchronized void driverThisBus(int a){
        //尝试获取锁
//        boolean b = lock.tryLock();

//        System.out.println(b);
        //加锁
        lock.lock();





        try {
            id = a;
            System.out.println(id + "开这辆车：" + carCode + "。" + time++);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //解锁
            lock.unlock();
        }
    }
}